import { GetAppVersion } from "@/api/Ctrls.js"
import { Toast } from '@/utils/tools.js'
import store from 'vuex'

function Updater() {
	this.updataInfo = {}
}
Updater.prototype = {
	constructor: Updater,
	check() {
		//H5默认不更新
		// #ifdef H5
		return {
			isUpdate: false,
		}
		// #endif
		return new Promise(async resolve => {
			try {
				const { data, success } = await GetAppVersion();
				this.updataInfo = data;
				const { version, mandatory, url } = data;
				const { versionCode } = await getAppVersion();
				console.log('最新版号', version,'本地的版号', versionCode)
				//存储更新信息
				const isUpdate = chechVersion(version, versionCode);
				console.log('是否更新：', isUpdate)
				if (isUpdate) {
					if (mandatory == 1) {
						uni.navigateTo({
							url: '/pages/upgrade',
						})
					}
					//wgt更新默认执行
					if (mandatory == 2) {
						this.downloadApk(url, 'wgt',{}, ({ file }) => {
							this.installWgt(file);
						})
					}
				}
				resolve({
					// 强制更新返回true
					isUpdate: isUpdate && mandatory == 1,
				})

			} catch (e) {
				resolve({
					isUpdate: false,
				})
				console.log(e)
				//TODO handle the exception
			}
		})
	},
	downloadApk(upUrl, type='apk',change, success) {
		//不是安装包 打开外部浏览器
		// if (!/\.apk$/.test(upUrl) && !/\.wgt$/.test(upUrl)) {
		// 	//调用外部浏览器打开更新地址
		// 	plus.runtime.openURL(upUrl, function() {
		// 		plus.nativeUI.toast("下载地址打开错误");
		// 	});
		// 	return
		// }
		const { platform } = uni.getSystemInfoSync();
		if (platform === 'ios') {
			Toast('请去App Store更新！')
		}
		return new Promise(async (resolve, reject) => {
			console.log('start download', upUrl);
			let task = plus.downloader.createDownload(upUrl, {}, (d, status) => {
				// console.log('d.filename, status===>', d.filename, status)
				console.log(status)
				if (status === 200) {
					// 直接安装
					if(type=='apk'){
						this.installApk(d)
					}
					
					//为页面执行安装按钮 避免自动安装失败
					this.apkFile = d.filename
					this.file = d;
					success && success({
						file: d
					})
					console.log('file==>', file)
					resolve(file);
				} else {
					
					reject(false)
				}
			})
			task.addEventListener("statechanged", (download, status) => {
				change && change({
					downloadTotal: download.totalSize,
					downloadSize: download.downloadedSize,
				})
			}, false);
			task.start();
		})
	},
	//安装APK 
	installApk(file = this.file) {
		return new Promise((resolve, reject) => {
			plus.nativeUI.showWaiting("正在读取更新文件...");
			plus.runtime.install(plus.io.convertLocalFileSystemURL(file.filename), {}, () => {
				plus.nativeUI.closeWaiting();
			}, (e) => {
				plus.nativeUI.closeWaiting();
				plus.nativeUI.alert("安装更新文件失败[" + e.code + "]：" + e.message);
			});
		})
	},
	//安装WWgt
	installWgt(file = this.file) {
		return new Promise((resolve, reject) => {
			// plus.nativeUI.showWaiting("安装更新文件...");
			plus.runtime.install(file.filename, {force:true}, () => {
				// //延迟执行避免启动时  页面跳转
				setTimeout(() => {
					//跳转至更新页   重新打开APP
					uni.navigateTo({
						url: '/pages/upgrade?type=2',
					})
				}, 10000)

				// plus.nativeUI.closeWaiting();
				// plus.nativeUI.showWaiting("安装完成，正在重启APP...");
				// setTimeout(() => {
				// 	plus.nativeUI.closeWaiting();
				// 	//更新完成  清空存储的版本信息
				//store.commit('general/CLEAR_UPINFO')
				// 	plus.runtime.restart();
				// }, 1000)
			}, (e) => {
				console.log(e)
				plus.nativeUI.closeWaiting();
				plus.nativeUI.alert("安装更新文件失败[" + e.code + "]：" + e.message);
			});
		})
	},
	getAppVersion() {
		return new Promise((resolve, reject) => {
			try {
				plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => {
					let version = wgtinfo.version;
					let versionCode = wgtinfo.versionCode;
					resolve(wgtinfo);
				});
			} catch (e) {
				console.log(e)
				reject("1.0.0");
			}
		});
	}
}

export default new Updater();


function getAppVersion() {
	return new Promise((resolve, reject) => {
		try {
			plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => {
				let version = wgtinfo.version;
				let versionCode = wgtinfo.versionCode;
				resolve(wgtinfo);
			});
		} catch (e) {
			console.log(e)
			reject("1.0.0");
		}
	});
}


//版本versionCode比较
/**curV  本地版本
 * reqV  app版本号
 * **/
function chechVersion(curV, reqV) {
	if (curV && reqV) {
		return Number(curV) > Number(reqV)
	} else {
		//输入为空
		return false;
	}
}

function chechVersion1(curV, reqV) {
	if (curV && reqV) {
		//将两个版本号拆成数字
		var arr1 = curV.split('.'),
			arr2 = reqV.split('.');
		var minLength = Math.min(arr1.length, arr2.length),
			position = 0,
			diff = 0;
		//依次比较版本号每一位大小，当对比得出结果后跳出循环
		while (position < minLength && ((diff = parseInt(arr1[position]) - parseInt(arr2[position])) == 0)) {
			position++;
		}
		diff = (diff != 0) ? diff : (arr1.length - arr2.length);
		//若curV大于reqV，则返回true
		return diff > 0;
	} else {
		//输入为空
		return false;
	}
}
